﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using CALTypeLib;
using UnisysMassiveImporter_v2.Entidades.Documentos;
using UnisysMassiveImporter_v2.Entidades.Mensajes;
using UnisysMassiveImporter_v2.Entidades.Configuracion;


namespace UnisysMassiveImporter_v2.Negocio.InfoImage
{
    public class IIF_WorkItem : IIF_Connection
    {

       
        #region Recursos Globales

        //string inputQueue;
        

        private CALDocument calDocument;
        private CALFormFields calFormFields;
        private CALIndexFields calIndexFields;
        private CALPage calPage;
        private CALPages calPages;
        private CALQueue calQueue = new CALQueue();
        //private CALQueues calQueues;
        private CALWorkitemInfo calWorkItemInfo;
        //private CALWorkitemWorkstepList calWorkitemWorkstepList;


       // private const long OMDCLIENTCREATE_APPLYFUNCSEC = 0x0001;
        //private const long OMDENUMCLIENTLISTADD_RETAIN = 0x0001;
        //private const long OMDDPAGEIMAGEWRITE_INCLUDE_MARKUPS = 0x0001;
        /*
        private const int CALQueueListWorkset = 64;
        private const int CALQueueListWorkstep = 128;
        private const int CALQueueListUserOnly = 512;
        */
        private InfoMessage infoMessage;

        #endregion

        public bool CreateWorkItem(IDoc doc, ref Configuration appConfig, ref Thread_Config threadConf)
        {
            infoMessage = new InfoMessage();


            if (doc is Document)
            {
                Document document = (Document)doc;




                if ((!(document.docName.Equals(""))) || (!(document.docClass.Equals(""))))
                {
                    // Creando workitem

                    infoMessage.sendMessage("Creando Workitem", InfoMessage.Information_Message, 611, threadConf.Name,ref appConfig);

                    calWorkItemInfo = calClient.CreateDocument(document.docName, document.docClass);
                    calClientListItem = calClientList.Add(calWorkItemInfo.ObjID, ClientListAddConstants.calAddRetain);
                    calDocument = calClientListItem.Open(OpenConstants.calOpenReadWrite);
                    calFormFields = calDocument.FormFields(FieldConstants.calFieldsNoViews);
                    // Workitem creado con éxito.

                }


                else
                {

                    CriticalMessage cMessage=new CriticalMessage("No se encontraron los campos de indexacion(docName o docClass) correspondientes a la clase documental.",new Exception("El documento no fue bien indexado"),CriticalMessage.IIF_Error,215,threadConf.Name,false);
                    cMessage.sendMessage(ref appConfig);
                    return false;
                }


                calFormFields.Find("UNI_DOC").set_Value(1, document.docUnit);


                for (int j = 0; j < document.indexFields.Count; j++)
                {

                    IndexField index = (IndexField)document.indexFields[j];
                    if (index.name.Equals("IMAGEN"))
                    {

                        for (int i = 0; i < document.images.Count; i++)
                        {
                            Images images = (Images)document.images[i];
                            if (images.name.Equals(index.value))
                            {

                                if (System.IO.File.Exists(images.path))
                                {
                                    string extension=images.path.Split('.')[1];
                                    if (extension.ToUpper().Equals("PDF"))
                                    {

                                        infoMessage.sendMessage("Intentando asignar imagen [" + images.name + "] al documento [" + document.docName + "].", InfoMessage.Information_Message, 612, threadConf.Name, ref appConfig);


                                        calDocument.ImportPages(images.path,images.name);

                                        
                                        infoMessage.sendMessage("Imagen [" + images.path + "] fue asignada al documento [" + document.docName + "] exitosamente.", InfoMessage.Success_Message, 283, threadConf.Name, ref appConfig);
                                        break;//solo un pdf se metera y no se combinara con imagenes tiff, por desicion del bcr

                                    }
                                    else if ((extension.ToUpper().Equals("TIF")) || (extension.ToUpper().Equals("TIFF")))
                                    

                                    {
                                        infoMessage.sendMessage("Intentando asignar imagen [" + images.name + "] al documento [" + document.docName + "].", InfoMessage.Information_Message, 612, threadConf.Name, ref appConfig);
                                        calPages = (CALPages)calDocument.Pages;
                                        calPages.Add(calPages.Count + 1, images.name, images.path);
                                        infoMessage.sendMessage("Imagen [" + images.path + "] fue asignada al documento [" + document.docName + "] exitosamente.", InfoMessage.Success_Message, 283, threadConf.Name, ref appConfig);
                                        break;
                                    }
                                    
                                }
                                else
                                {
                                    CriticalMessage message = new CriticalMessage();
                                    message.sendMessage("Imagen [" + images.path + "] asociada al documento [" + document.docName + "] no fue localizada.", new Exception("Imagen no encontrada."), CriticalMessage.Configuration_Error, 283, threadConf.Name, false, ref appConfig);
                                    calDocument.Close(CloseConstants.calCloseAbortChanges);
                                    return false;
                                }

                            }
                        }


                    }
                    else
                    {
                        infoMessage.sendMessage("Campo de Indexacion Encontrado con nombre: " + index.name + " y valor: " + index.value + " del documento: " + document.docName, InfoMessage.Information_Message, 581, threadConf.Name, ref appConfig);
                        calFormFields.Find(index.name).set_Value(1, index.value);
                    }

                }

                infoMessage.sendMessage("Intentando guardar el documento [" + document.docName + "] en workflow.", InfoMessage.Information_Message, 613, threadConf.Name, ref appConfig);

                //GUARDAR DOCUMENTO E IMPORTARLO
                calDocument.Save();
                calDocument.Close(CloseConstants.calCloseSaveChanges);
                infoMessage.sendMessage("Enviando documento [" + document.docName + "] a workflow.", InfoMessage.Information_Message, 614, threadConf.Name, ref appConfig);
                
               // 
                bool resultado=SendToWorkflow(threadConf.InputQueue, document.docName,ref appConfig,ref threadConf);
                if (! resultado )
                    return resultado;
                infoMessage.sendMessage("Limpiando escritorio del usuario...", InfoMessage.Information_Message, 571, threadConf.Name, ref appConfig);

                CheckStatusIIFClientDesktop();
                return true;

            }
            else
            {
                return false;
            }
        }





        public bool SendToWorkflow(string queueName, string docName,ref Configuration appConfig, ref Thread_Config threadConf)
        {
            try
            {
                infoMessage = new InfoMessage();

                //Establecer el nombre de la colaw.
                infoMessage.sendMessage("Estableciendo el workstep [" + queueName + "] a donde será enviado el workitem...", InfoMessage.Information_Message, 615, threadConf.Name, ref appConfig);
               calQueue.Name = queueName;
               infoMessage.sendMessage("Workstep [" + queueName + "] asignado.", InfoMessage.Information_Message, 615, threadConf.Name, ref appConfig);

                 
                calQueue.Type = QueueTypeConstants.calQueueTypeWorkstep;
                infoMessage.sendMessage("Workstep [" + queueName + "] asignado exitosamente.", InfoMessage.Information_Message, 615, threadConf.Name, ref appConfig);

               
                if (queueName.Equals(""))
                {
                    infoMessage.sendMessage("No se encontro un nombre de workstep de salida para el documento [" + docName + "] por lo que será enviado a la cola [Default].", InfoMessage.Information_Message, 616, threadConf.Name, ref appConfig);
                    calClientListItem.SendToDefault(SendConstants.calSendDiscard);
                    infoMessage.sendMessage("Workitem [" + docName + "] enviado a la cola [Default].", InfoMessage.Success_Message, 284, threadConf.Name, ref appConfig);
                }
                else
                {
                    calClientListItem.Send(calQueue, SendConstants.calSendDiscard);
                    infoMessage.sendMessage("Workitem [" + docName + "] enviado a la cola [" + queueName + "].", InfoMessage.Success_Message, 285, threadConf.Name, ref appConfig);
                }
                return true;
            }
            catch (Exception exc)
            {
                CriticalMessage criticalMessage = new CriticalMessage();
                criticalMessage.sendMessage(exc.Message, new Exception("[SendWorkitemToWorkflow] ERROR"), CriticalMessage.IIF_Error, 214, threadConf.Name, false, ref appConfig);
                return false;
            }
        }
    }
}
